package com.xuyanze.domain;

import com.xuyanze.config.properties.ApiDocProperties;
import com.xuyanze.core.manager.PathManager;
import com.xuyanze.model.LoginSession;
import com.xuyanze.utils.HttpUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * @author ：lzy
 * @date ：2021-10-25
 * @description：登录上下文
 */
public class LoginContext {

    private LoginSession loginSession;

    private ApiDocProperties apiDocProperties;

    // TODO 地址信息
    private static final String LOGIN_URL = "http://";

    public LoginContext(ApiDocProperties apiDocProperties){
        this.apiDocProperties = apiDocProperties;
    }


    /**
     * 用户登录
     */
    public void login() {
        Map<String,String> paramMap = new HashMap<>();
        paramMap.put("userName", apiDocProperties.getAccount());
        paramMap.put("password", apiDocProperties.getPassword());
        paramMap.put("sessionAdminName", apiDocProperties.getUserName());
        String cookie = HttpUtils.getCookie(LOGIN_URL, paramMap, null);

        loginSession = new LoginSession();
        loginSession.setAccount(apiDocProperties.getAccount());
        loginSession.setPassword(apiDocProperties.getPassword());
        loginSession.setUserName(apiDocProperties.getUserName());
        loginSession.setCookie(cookie);
    }

    /**
     * 获取cookie
     * @return
     */
    public String getCookie() {
        return Optional.ofNullable(loginSession).map(session -> session.getCookie()).orElseGet(() -> {
            login();
            return loginSession.getCookie();
        });
    }

    /**
     * 获取登录session
     * @return
     */
    public LoginSession getLoginSession() {
        return Optional.ofNullable(loginSession).orElseGet(() -> {
            login();
            return loginSession;
        });
    }

    public ApiDocProperties getApiDocProperties() {
        return apiDocProperties;
    }

    public void setApiDocProperties(ApiDocProperties apiDocProperties) {
        this.apiDocProperties = apiDocProperties;
    }
}
